__author__ = 'l4537'
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#coding:utf-8
import re
from san import models
from django.db.models import Q
def Re(res,total,id = "1"):
    if id == "1":
        data = re.findall(str(res),total)
    if id == "2":
        data = re.findall(str(res),total,re.M)
    return data

class San():
    def __init__(self,data):
        self.data = data
#        print(self.data)
    def Index(self):
        a = Re(r'(\d+\s+\d+\s+\d+|\d+\s+\d+)\s+(\S{6})\s+\S{2}\s+(\S{2,3})\s+(\S+)\s+FC\s+(\s|\S+\s+..:..:..:..:..:..:..:..)',self.data)
        Index ={}
        for i in a:
            port_mess = i[0].split(" ")
            while "" in port_mess:
                port_mess.remove("")
            Index[port_mess[0]] = {}
            wwn_mess = i[4].split(" ")
            while "" in wwn_mess:
                wwn_mess.remove("")
            while "\n" in wwn_mess:
                wwn_mess.remove("\n")
            if len(port_mess) == 3:
                Index[port_mess[0]]["slot"] = port_mess[1]
                Index[port_mess[0]]["port"] = port_mess[2]
                Index[port_mess[0]]["fcid"] = i[2]
                Index[port_mess[0]]["speed"] = i[3]
                if len(wwn_mess) ==2 :
                    Index[port_mess[0]]["type"] = wwn_mess[0]
                    Index[port_mess[0]]["wwn"] = wwn_mess[1]
                else:
                    Index[port_mess[0]]["type"] = ""
                    Index[port_mess[0]]["wwn"] = ""
            if len(port_mess) == 2:
                Index[port_mess[0]]["slot"] = ""
                Index[port_mess[0]]["port"] = port_mess[1]
                Index[port_mess[0]]["fcid"] = i[2]
                Index[port_mess[0]]["speed"] = i[3]
                if len(wwn_mess) ==2 :
                    Index[port_mess[0]]["type"] = wwn_mess[0]
                    Index[port_mess[0]]["wwn"] = wwn_mess[1]
                else:
                    Index[port_mess[0]]["type"] = ""
                    Index[port_mess[0]]["wwn"] = ""
        return Index
    def Porterr(self):
        data_indx = self.Index()
        a = Re(r"(\d+):\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)",self.data)
        for i in data_indx:
            for ii in a:
                if i == ii[0]:
                    data_indx[i]["TX"] = ii[1]
                    data_indx[i]["RX"] = ii[2]
                    data_indx[i]["enc_in"] = ii[3]
                    data_indx[i]["crc_err"] = ii[4]
                    data_indx[i]["crc_g_eof"] = ii[5]
                    data_indx[i]["two_shrt"] = ii[6]
                    data_indx[i]["two_long"] = ii[7]
                    data_indx[i]["bad_eof"] = ii[8]
                    data_indx[i]["enc_out"] = ii[9]
                    data_indx[i]["disc_c3"] = ii[10]
                    data_indx[i]["link_fail"] = ii[11]
                    data_indx[i]["loss_sync"] = ii[12]
                    data_indx[i]["loss_sig"] = ii[13]
                    data_indx[i]["frjt"] = ii[14]
                    data_indx[i]["fbsy"] = ii[15]
                    data_indx[i]["timeout_tx"] = ii[16]
                    data_indx[i]["timeout_rx"] = ii[17]
                    data_indx[i]["pcx_err"] = ii[18]
        return data_indx
    def Sfpshow(self):
        Indextotal = self.Porterr()
        return Indextotal
    def Hardware(self):
        pass
    def Alias(self):
        a = Re(r'alias:\s(.*)\n\s+(..:..:..:..:..:..:..:..)',self.data)
        print(a)
    def Zone(self):
        pass
#单个更新
def sanportinport(nid):
    status = ""
    a = models.Doment.objects.filter(id = nid).first()
    sanid = a.san_id
    from scriptd import djsan
    a = djsan.San(a.text)
    switch = a.Sfpshow()
    for i in switch:
        if switch[i]["wwn"] != "":
            a = models.Wwn.objects.get_or_create(wwn=switch[i]["wwn"])
            obj_del = models.Sanport.objects.first()
    try:
        obj_del = models.Sanport.objects.filter(san_id = sanid).delete()
    except Exception as e:
        status = e
    # obj_del = models.San.objects.filter(id=8).first()
    # obj_del.models.San_set.all().delete()
    for i in switch:
        switch[i]["san_id"] = sanid
        switch[i]["index"] = i
        a = models.Sanport.objects.create(**switch[i])
        if switch[i]["wwn"] != "":
            try:
                b = models.Wwn.objects.get(wwn = switch[i]["wwn"])
                b.Sanport_wwn_id = a.id
                b.save()
            except Exception as e:
                status = e
    if status == "":
        status = "ok"
    return status
#所有更新
def sanupdataall():
    ret = {"status": True, "error": None, "data": None}
    sanobj = models.San.objects.filter(Q(prodname = "Brocade") | Q(prodname=u"惠普"))
    for i in sanobj:
        a = models.Doment.objects.filter(san_id=i.id).order_by("-dotime").first()
        if a:
            print(a.id)
            status = sanportinport(a.id)
            print(status)
    for i in sanobj:
        sanport = models.Sanport.objects.filter(san_id = i.id)
        if sanport:
            onlineport = 0
            availableport = 0
            nomodelport = 0
            for p in sanport:
                if p.speed == "Online":
                    onlineport +=1
                elif p.speed == "No_Light":
                    availableport +=1
                elif p.speed =="No_Module":
                    nomodelport += 1
            otherport = int(len(sanport)) - int(availableport) - int(nomodelport)
            i.onlineport = onlineport
            i.availableport = availableport
            i.nomodelport = nomodelport
            i.otherport = otherport
            i.save()
    return ret